#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>

bool is_letter(char c)
{
	if (c >= 'a' && c <= 'z')
	{
		return true;
	}
	if (c >= 'A' && c <= 'Z')
	{
		return true;
	}
	return false;
}

int main()
{
	int d = 3;//密钥1--凯撒移位
	int y = 8;//密钥2--栅栏加密列数
	char ciphertext[] = "wah tetea  t tcwae licneolkeicl mgk tyh ";

	//凯撒移位-遍历字符串，再将是字母的移位d

	char* p = ciphertext;
	while (*p != '\0')
	{
		while (*p == ' ')
		{
			p++;
		}
		while (is_letter(*p))
		{
			(*p) += d;
			if (!is_letter(*p))//移位时超出范围
			{
				(*p) -= d;
				int count = d;
				while (count)
				{
					(*p)++;
					count--;
					if (!is_letter(*p))
					{
						*p = 'a';//*p为z+1的时候
					}
				}
			}
			p++;
		}
	}
	

	FILE* pf = fopen("myscreat.txt", "w");

	fprintf(pf, "%s", ciphertext);

	char* plaintext = (char*)malloc(sizeof(char) * 100);
	strcpy(plaintext, ciphertext);

	//凯撒移位复原
	p = plaintext;
	while (*p != '\0')
	{
		while (*p == ' ')
		{
			p++;
		}
		while (is_letter(*p))
		{
			(*p) -= d;
			if (!is_letter(*p))//移位时超出范围
			{
				(*p) += d;
				int count = d;
				while (count)
				{
					(*p)--;
					count--;
					if (!is_letter(*p))
					{
						*p = 'z';//*p为a-1的时候
					}
				}
			}
			p++;
		}
	}

	//栅栏解密
	int len = strlen(plaintext);
	int row = len / y;//求出行数以便放置字符串到二维数组中
	char arr[100][100] = { 0 };
	int i, j;
	int k = 0;
	for (i = 0; i < y; i++)
	{
		for (j = 0; j < row; j++)
		{
			arr[j][i] = plaintext[k++];
		}
	}

	for (i = 0; i < row; i++)
	{
		for (j = 0; j < y; j++)
		{
			printf("%c", arr[i][j]);
		}
	}
  printf("\n");
	return 0;
}
